package com.ponxu.mb.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.ponxu.db.DBException;
import com.ponxu.log.Log;
import com.ponxu.log.LogFactory;
import com.ponxu.mb.Global;
import com.ponxu.mb.db.ConnectionManager;
import com.ponxu.mb.exception.BlogException;

/**
 * 数据库管理, 安装等
 * 
 * @author xwz
 * 
 */
public class DBFilter implements Filter {
	private static final Log LOG = LogFactory.getLog();

	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		LOG.debug("----------DBFilter begin----------");
		try {
			if (Global.readBoolean("INSTALLED")) {
				chain.doFilter(req, res);
				ConnectionManager.commit();
			} else {
				install(req, res);
			}
		} catch (DBException e) {
			LOG.warn("Occur DB Error!");
			ConnectionManager.rollback();
			throw e;
		} finally {
			ConnectionManager.release();
			LOG.debug("----------DBFilter end----------");
		}
	}

	/**
	 * 安装数据库处理
	 * 
	 * @param req
	 * @param res
	 */
	private void install(ServletRequest req, ServletResponse res) {
		LOG.debug("----------INSTALL----------");
		// 接收参数, 并设置到配置中
		String host = req.getParameter("host");
		Global.write("HOST", host);

		try {
			// 尝试加载数据库, 成功 则保持配置
			ConnectionManager.init();
			Global.save();
		} catch (BlogException e) {
			String msg = e.getMessage();
			LOG.debug(msg);
		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
		ConnectionManager.init();
	}

	public void destroy() {
		ConnectionManager.destroy();
	}

}
